package com.my.thread.pool;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by ZhongGang
 * at 2018/7/20 11:46
 */
public class AsyncResult<V> {
    private boolean completed = false;
    private V result = null;
    private ReentrantLock lock = new ReentrantLock();
    private Condition completedCondition = lock.newCondition();

    public AsyncResult() {
    }

    public AsyncResult(V result) {
        this.result = result;
    }

    public V get() {
        try {
            lock.lock();
            while (!completed) {
                try {
                    this.completedCondition.await();
                } catch (InterruptedException e) {
                    throw new UnsupportedOperationException("interrupted...");
                }
            }

            return this.result;
        } finally {
            lock.unlock();
        }
    }

    public boolean isCompleted() {
        try {
            this.lock.lock();
            return completed;
        } finally {
            this.lock.unlock();
        }
    }

    public void setCompleted(boolean completed) {
        try {
            this.lock.lock();
            if (completed) {
                this.completedCondition.signalAll();
            }
            this.completed = completed;
        } finally {
            this.lock.unlock();
        }
    }

    public V getResult() {
        try {
            this.lock.lock();
            return result;
        } finally {
            this.lock.unlock();
        }
    }

    public void setResult(V result) {
        try {
            this.lock.lock();
            this.result = result;
        } finally {
            this.lock.unlock();
        }
    }
}
